#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#include "config.h"
#include "symbol.h"
#include "debug.h"
#include "parser.h"
#include "scanner.h"

extern struct cminus_token t;

FILE *output_fp = NULL;
FILE *input_fp = NULL;
char *output_file_name = NULL;
char *input_file_name = NULL;

static void usage()
{
  printf("Usage:cminus-compiler -o asm_source -f c_source\n");
}

int main(int argc, char *argv[])
{
  int ch;

  /*parse args*/
  while ((ch = getopt(argc, argv, "o:f:")) != -1)
  {
    switch (ch)
    {
      case 'o':
        output_file_name = optarg;
        break;
      case 'f':
        input_file_name = optarg;
        break;
      default:
        printf("unknow option\n");
        usage();
        exit(-1);
    }
  }

  if (NULL == output_file_name || NULL == input_file_name)
  {
    usage();
    exit(-1);
  }

  /*open file for parsing*/
  input_fp = fopen(input_file_name, "r");

  if (NULL == input_fp)
  {
    __ERROR_MSG("error when open %s:%s\n", input_file_name,
                strerror(errno));
    exit(-1);
  }

  /*open file for writing asm code*/
  output_fp = fopen(output_file_name, "w+");

  if (NULL == output_fp)
  {
    __ERROR_MSG("error when open %s:%s\n", output_file_name,
                strerror(errno));
    exit(-1);
  }

  sym_table_init();

  t = get_token();
  program();

  return 1;
}

